import win32con
import win32api
import win32gui
import time
import xlrd
import xlwt
import win32clipboard
import pandas as pd

#点击键盘的f键，其中70是f虚拟键码
def key(key):
    win32api.keybd_event(key,0,0,0)     #代表按下f键
    time.sleep(0.02)
    win32api.keybd_event(key, 0, win32con.KEYEVENTF_KEYUP, 0)  #释放f键


def ctrlA():
    #按下ctrl+a，全选
    #17为ctrl键码值，65为a的键码值
    win32api.keybd_event(17,0,0,0)
    win32api.keybd_event(65,0,0,0)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(65, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(1)


def ctrlC():
    #按下ctrl+c，67键码值为c
    win32api.keybd_event(17,0,0,0)
    win32api.keybd_event(67,0,0,0)
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(67, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(1)


def ctrlV():
    #按下ctrl+v
    win32api.keybd_event(17,0,0,0)
    win32api.keybd_event(86,0,0,0)  
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(1)

#鼠标现在屏幕上方的位置
def getMouse():
    pos = win32gui.GetCursorPos()     
    print(pos)
#鼠标移动
def move(x,y):
    win32api.SetCursorPos((x,y))                               

#鼠标左点击
def leftClick():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)


#鼠标右点击
def rightClick():
    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN | win32con.MOUSEEVENTF_RIGHTUP,0,0,0,0)



#保存excel
def export_excel(export):
   #将字典列表转换为DataFrame
   pf = pd.DataFrame(list(export))
#    #指定字段顺序
#    order = ['road_name','bus_plate','timeline','road_type','site']
#    pf = pf[order]
#    #将列名替换为中文
#    columns_map = {
#       'road_name':'路线',
#       'bus_plate':'车牌',
#       'timeline':'时间',
#       'road_type':'方向',
#       'site':'站点'
#    }
#    pf.rename(columns = columns_map,inplace = True)
   #指定生成的Excel表格名称
   file_path = pd.ExcelWriter('手机号搜不到用户.xlsx')
   #替换空单元格
   pf.fillna(' ',inplace = True)
   #输出
   pf.to_excel(file_path,encoding = 'utf-8',index = False)
   #保存表格
   file_path.save()


def read_excel(src):
    # 打开文件
    workBook = xlrd.open_workbook(src)

    # 1.获取sheet的名字
    # 1.1 获取所有sheet的名字(list类型)
    # allSheetNames = workBook.sheet_names()
    # print(allSheetNames)

    # 1.2 按索引号获取sheet的名字（string类型）
    # sheet1Name = workBook.sheet_names()[0]
    # print(sheet1Name)

    # 2. 获取sheet内容
    ## 2.1 法1：按索引号获取sheet内容
    sheet1_content1 = workBook.sheet_by_index(0); # sheet索引从0开始
    ## 2.2 法2：按sheet名字获取sheet内容
    # sheet1_content2 = workBook.sheet_by_name('Sheet1')

    # 3. sheet的名称，行数，列数
    # print(sheet1_content1.name,sheet1_content1.nrows,sheet1_content1.ncols)

    # 4. 获取整行和整列的值（数组）
    # rows = sheet1_content1.row_values(3); # 获取第四行内容
    cols1 = sheet1_content1.col_values(0); # 获取第1列内容
    cols2 = sheet1_content1.col_values(1)
    cols = dict(zip(cols1, cols2))
    return cols
    # 5. 获取单元格内容(三种方式)
    # print(sheet1_content1.cell(1, 0).value)
    # print(sheet1_content1.cell_value(2, 2))
    # print(sheet1_content1.row(2)[2].value)

    # 6. 获取单元格内容的数据类型
    # Tips: python读取excel中单元格的内容返回的有5种类型 [0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error]
    # print(sheet1_content1.cell(1, 0).ctype)

#把文本读取到win10的paste缓冲区
def setPaste(paste):
    # set clipboard data
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(paste)
    win32clipboard.CloseClipboard()

#获取paste内容
def getPaste():
    # get clipboard data
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()
    return data

def timeSleep(s):
    time.sleep(s)

hwnd_title= dict()
def get_all_hwnd(hwnd,mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})


notFound={}
wxNotFound="该用户不存在"

def isExist(userPhone):
    global hwnd_title
    win32gui.EnumWindows(get_all_hwnd, 0)
    for h,t in hwnd_title.items():
        if t is not "":
            # print(userPhone,t)           
            if(wxNotFound in t):
                notFound.update({userPhone:t})
    hwnd_title= dict()

if __name__ == '__main__':
    if(win32api.GetSystemMetrics(win32con.SM_CXSCREEN)==1920):
        print("请输入excle路径地址")
        src=input()
        print("请设置邀请语")
        invite=input()
        cols=read_excel(src)
        for f, col in cols.items():
            #1.取出第一个手机号
            print("读取姓名"+f+"读取手机号--"+str(int(col)))
            setPaste(str(int(col)))
            #2.移动鼠标
            move(821,436)
            timeSleep(1)
            #3.鼠标左击
            leftClick()
            #4.粘贴
            ctrlV()
            #移动到查找
            move(1116,430)
            timeSleep(1)
            leftClick()
            #睡眠三秒防止网络缓慢
            timeSleep(1)
            #获取句柄信息判断企业微信用户是否存在
            isExist(str(int(col)))
            timeSleep(3)
            #如果搜不到用户
            move(1090,575)
            leftClick()
            #移动到添加
            move(1071,535)
            timeSleep(1)
            leftClick()
            #去掉邀请语
            move(1092,497)
            timeSleep(1)
            leftClick()
            leftClick()
            #设置邀请语
            setPaste(f+":"+invite)
            timeSleep(3)
            leftClick()
            ctrlV()
            #移动到发送
            move(967,578)
            timeSleep(2)
            leftClick()
            #移动到搜索框
            move(916,428)
            timeSleep(1)
            leftClick()
            ctrlA()
            key(8)
            timeSleep(2)
        print(notFound)
        export_excel(notFound)
        input('未搜到用户已保存到桌面,\n回车退出程序')
    else:
        print("请输入excle路径地址")
        src=input()
        print("请设置邀请语")
        invite=input()
        cols=read_excel(src)
        for f, col in cols.items():
            #1.取出第一个手机号
            print("姓名"+f+"读取手机号--"+str(int(col)))
            setPaste(str(int(col)))
            #2.移动鼠标
            move(650,343)
            timeSleep(1)
            #3.鼠标左击
            leftClick()
            #4.粘贴
            ctrlV()
            #移动到查找
            move(876,341)
            timeSleep(1)
            leftClick()
            #睡眠三秒防止网络缓慢
            timeSleep(1)
            #如果搜不到用户
            #获取句柄信息判断企业微信用户是否存在
            isExist(str(int(col)))
            move(848,484)
            leftClick()
            #移动到添加
            move(847,450)
            timeSleep(1)
            leftClick()
            #去掉邀请语
            move(853,409)
            timeSleep(1)
            leftClick()
            leftClick()
            #设置邀请语
            setPaste(f+":"+invite)
            timeSleep(3)
            leftClick()
            ctrlV()
            #移动到发送
            move(700,479)
            timeSleep(2)
            leftClick()
            #移动到搜索框
            move(675,343)
            timeSleep(1)
            leftClick()
            ctrlA()
            key(8)
            timeSleep(2)
        print(notFound)
        export_excel(notFound)
        input('未搜到用户已保存到桌面,\n回车退出程序')
    




        



 